import os
import numpy as np


def delete_unused_nii_files(nii_folder_path):
    """删除指定路径下的，与病情诊断无关的 nii 文件

    :param nii_folder_path: 待处理的nii的存储路径
    """
    for nii_name in os.listdir(nii_folder_path):
        if ('RESP' in nii_name) or ('ep2d' in nii_name) or ('in-opp' in nii_name) \
                or ('cor' in nii_name) or ('test' in nii_name) or ('fs' not in nii_name):
            if ('T2WI' in nii_name) or ('Pre' in nii_name) or ('Arterial' in nii_name) \
                    or ('Venous' in nii_name) or ('Delay' in nii_name):
                break  # 不删除已经改过名字的nii（防止误删）
            delete_file_path = os.path.join(nii_folder_path, nii_name)
            os.remove(delete_file_path)
            print("Delete: ", delete_file_path)


def rename_nii_files_by_phases(nii_folder_path):
    """

    :param nii_folder_path:待处理的nii的存储路径
    :return:
    """
    nii_file_list = os.listdir(nii_folder_path)
    if len(nii_file_list) != 5:
        print("请根据相关文档，手动删除多余的nii文件，保留有效文件\n"
              "目标路径:", nii_folder_path)
        return
    if nii_file_list[0].find('_') == -1:
        print("该路径下文件不需要重命名\n目标路径:", nii_folder_path)
        return
    patient_info = nii_folder_path.split('\\')[-1]
    patient_name = patient_info.split('_')[0]  # 根据敏感度需要隐藏掉患者的姓名
    study_id = patient_info.split('_')[1]
    print(nii_file_list)

    nii_number_list = []
    for nii_name in nii_file_list:
        nii_number_list.append(int(nii_name.split('-')[0]))
    print(nii_number_list)

    phase = ('T2WI', 'Pre', 'Arterial', 'Venous', 'Delay')
    import sys
    max = sys.maxsize
    for i in range(5):
        min_index = np.argmin(nii_number_list)
        min_index_filename = nii_file_list[min_index]
        old_file_path = os.path.join(nii_folder_path, min_index_filename)
        new_file_path = os.path.join(nii_folder_path, f"{patient_name}-{study_id}-{i}-{phase[i]}.nii")
        os.rename(old_file_path, new_file_path)
        print(f"Renamed {old_file_path} to {new_file_path}")
        nii_number_list[min_index] = max



if __name__ == "__main__":
    # 以2022为例
    all_path = r"C:\Users\18049\Desktop\nii"
    nii_path_2022 = all_path + r"\2_classification_nii\metastasis 2022"
    # 遍历根文件夹下的所有子文件夹
    # 目标结构：metastasis 2022\XXX XXX XXX_M000xxxxx\\15_t1_vibe_fs_tra_bh_p2_two scans.nii
    # for patient_dcm_folder in os.listdir(nii_path_2022):
    #     patient_dcm_folder_path = os.path.join(nii_path_2022, patient_dcm_folder)  # C:\..\CHEN YI JIANG_M00xxxxx
    #     if os.path.isdir(patient_dcm_folder_path):  # 检查是否是文件夹
    #         print('-' * 50, '\n', patient_dcm_folder, sep='')
    #         patient_nii_folder_path = os.path.join(nii_path_2022, patient_dcm_folder)  # 创建存放目标nii的文件夹
    #         delete_unused_nii_files(patient_nii_folder_path)  # 删除无关nii

    # Rename
    for patient_dcm_folder in os.listdir(nii_path_2022):
        patient_dcm_folder_path = os.path.join(nii_path_2022, patient_dcm_folder)  # C:\..\CHEN YI JIANG_M00xxxxx
        if os.path.isdir(patient_dcm_folder_path):  # 检查是否是文件夹
            print('-' * 50, '\n', patient_dcm_folder, sep='')
            patient_nii_folder_path = os.path.join(nii_path_2022, patient_dcm_folder)  # 创建存放目标nii的文件夹
            rename_nii_files_by_phases(patient_nii_folder_path)
